<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>城市天气</title>
  <link rel="stylesheet" href="./css/reset.css" />
  <link rel="stylesheet" href="./css/index.css" />
</head>

<body>
  <div class="wrap" id="app">
    <div class="search_form">
      <div class="logo"><img src="img/logo.png" alt="logo" /></div>
      <div class="form_group">
        <input type="text" v-model="city" class="input_txt" placeholder="请输入查询的天气" />
        <button class="input_sub" @click="fetchWeather">搜 索</button>
      </div>
      <div class="hotkey">
        <a href="javascript:;" @click="changeCity('北京')">北京</a>
        <a href="javascript:;" @click="changeCity('上海')">上海</a>
        <a href="javascript:;" @click="changeCity('广州')">广州</a>
        <a href="javascript:;" @click="changeCity('深圳')">深圳</a>
      </div>
    </div>
    <ul class="weather_list" v-if="weatherData">
      <li>
        <div class="info_type">
          <span class="iconfont">{{ weatherData.wea }}</span>
        </div>
        <div class="info_temp">
          <b>低：</b> {{ weatherData.tem2 }} ~ <b>高：</b> {{ weatherData.tem1 }}
        </div>
        <div class="info_date">{{ weatherData.date }}</div>
      </li>
    </ul>
    <div v-else-if="loading">加载中...</div>
    <div v-else-if="error">无法获取天气数据，请稍后再试。</div>
  </div>

  <!-- Vue.js CDN -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <!-- Axios CDN -->
  <script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
  <script>
    new Vue({
      el: "#app",
      data: {
        city: "北京", // 默认城市
        loading: false, // 加载状态
        error: false, // 错误状态
        weatherData: null, // 天气数据
      },
      mounted() {
        this.fetchWeather();
      },
      methods: {
        fetchWeather() {
          if (!this.city) {
            alert("请输入城市名称");
            return;
          }
          this.loading = true;
          this.error = false;
          const url = `http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=14847186&appsecret=SbNYrp85&city=${this.city}`;
          axios
            .get(url)
            .then((response) => {
              console.log(response.data); //一个调试工具，用于在浏览器控制台中打印 API 返回的数据，帮助你检查数据是否正确获取。它本身并不会影响页面是否显示天气信息。
              this.weatherData = response.data;
            })
            .catch((error) => {
              console.log(error);
              this.error = true;
            })
            .finally(() => {
              this.loading = false;
            });
        },
        changeCity(city) {
          this.city = city;
          this.fetchWeather();
        },
      },
    });
  </script>
</body>

</html>